package com.hospital.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.hospital.auth.feign.SystemService;
import com.hospital.auth.service.AuthService;
import com.hospital.common.constants.JwtConstants;
import com.hospital.common.constants.TokenConstants;
import com.hospital.common.domain.response.JwtResponse;
import com.hospital.common.domain.system.UserInfo;
import com.hospital.common.exceptions.ServiceException;
import com.hospital.common.result.R;
import com.hospital.common.utils.JwtUtils;
import com.hospital.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author：sjc
 * @Description:
 * @name：AuthServiceImpl
 * @Date：2024/10/18 19:37
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SystemService systemService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;


    @Override
    public JwtResponse login(UserInfo patientVo) {
        R<UserInfo> userR = systemService.findUserList(patientVo);
        if (userR.getCode() != 200) {
            throw new ServiceException("查找用户失败！", 401);
        }
        UserInfo user = userR.getData();
        if (StringUtils.isNull(user)) {
            throw new ServiceException("用户不存在", 401);
        }
        //生成userKey
        String userKey = IdUtil.simpleUUID().toString();
        Map map = new HashMap<>();
        map.put(JwtConstants.USER_KEY, userKey);
        //生成token
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey, JSONObject.toJSONString(user));
        //返回数据
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTimeStr("30Min");
        return jwtResponse;
    }

    @Override
    public UserInfo getInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        if(StringUtils.isNull(token)){
            throw new ServiceException("token为空");
        }
        String userKey = JwtUtils.getUserKey(token);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        UserInfo patientVo = JSONObject.parseObject(s, UserInfo.class);
        return patientVo;
    }

    @Override
    public void register(UserInfo patientVo) {

        R<UserInfo> patientVoR = systemService.selectUserName(patientVo.getUserName());
        if (patientVoR.getCode() != 200) {
            throw new ServiceException("用户已存在！", 401);
        }
        systemService.register(patientVo);
    }
}
